<?php

App::uses('AppController', 'Controller');

class AccountsController extends AppController {

	/**
	 * This controller does not use a model
	 *
	 * @var array
	 */
	public $uses = array('Account', 'Setting');

	public function add() {
		if ($this->request->is('post')) {
			$data = $this->request->data['Account'];
			$this->Account->create();
			$item = $this->Account->save(array(
				'name' => $data['name'],
				'money_unit' => $data['money_unit'],
				'icon_path' => $data['icon_path'],
				'balance' => floatval($data['balance']),
				'description' => $data['description'],
			));
			if ($item) {
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('Thất bại!');
			}
		}
	}

	public function edit($id) {
		$account = $this->Account->findById($id);
		if ($this->request->is('post') || $this->request->is('put')) {
			$data = $this->request->data['Account'];
			$this->Account->id = $id;
			$item = $this->Account->save(array(
				'name' => $data['name'],
				'money_unit' => $data['money_unit'],
				'icon_path' => $data['icon_path'],
				'balance' => floatval($data['balance']),
				'description' => $data['description'],
			));
			if ($item) {
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('Thất bại!');
			}
		}
		if (!$this->request->data) {
			$this->request->data = $account;
		}
		$this->render('add');
	}

	public function delete($id) {
		if ($this->request->is('post')) {
			$this->Account->delete($id);
		}
		$this->redirect(array('action' => 'index'));
	}

	public function index() {
		$list = $this->Account->find('all', array('order' => 'name asc'));

		//Return $list if request is from requestAction of view element
		if ($this->request->is('requested')) {
			return $list;
		}
		$this->set('accounts', $list);
		$grand_totals = $this->Account->query('SELECT SUM(income) - SUM(expense) as grand_total, money_unit FROM mm_accounts AS Account GROUP BY money_unit');
		$this->set('grand_totals', $grand_totals);
	}

	public function get_active() {
		$this->autoRender = false;
		$active_id = $this->Setting->getValue(Setting::KEY_ACTIVE_ACCOUNT);
		$active_account = $this->Account->findById($active_id);
		if ($this->request->is('requested')) {
			return $active_account;
		}
		$this->set('active_account', $active_account);
	}

	public function set_active($id) {
		$result = $this->Setting->setValue(Setting::KEY_ACTIVE_ACCOUNT, $id);
		if ($this->request->is('ajax')) {
			$this->log(__METHOD__ . ' called via Ajax', 'debug');
			$this->render('../Elements/Accounts/index');
		} else {
			$this->log(__METHOD__ . ' not called via Ajax', 'debug');
			if (false === $result) {
				$this->Session->setFlash('Đã chọn tài khoản.', 'default', array('class' => 'label-success'));
			}
		}
	}

}
